<template>
  <div class="generate-view">
    <!-- 生成配置区域 -->
    <el-card class="generate-config" v-if="!generatedReport">
      <template #header>
        <div class="card-header">
          <h3>
            <el-icon><Magic /></el-icon>
            {{ $t('workReports.generate.title') }}
          </h3>
          <p>{{ $t('workReports.generate.subtitle') }}</p>
        </div>
      </template>

      <el-form
        ref="formRef"
        :model="generateForm"
        :rules="generateRules"
        label-width="100px"
        @submit.prevent
      >
        <el-form-item :label="$t('workReports.generate.form.reportType')" prop="type">
          <el-radio-group v-model="generateForm.type" @change="handleTypeChange">
            <!-- {{ AURA-X: Modify - 修复Element Plus兼容性，将label改为value. Approval: 寸止(ID:fix-element-plus-radio). }} -->
            <el-radio-button
              v-for="option in reportTypeOptions"
              :key="option.value"
              :value="option.value"
            >
              {{ option.label }}
            </el-radio-button>
          </el-radio-group>
          <div class="type-description">
            {{ getTypeDescription(generateForm.type) }}
          </div>
        </el-form-item>

        <el-form-item
          v-if="generateForm.type === 'DAILY'"
          :label="$t('workReports.generate.form.selectDate')"
          prop="startDate"
        >
          <el-date-picker
            v-model="generateForm.startDate"
            type="date"
            :placeholder="$t('workReports.generate.form.selectDate')"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 300px"
          />
        </el-form-item>

        <el-form-item
          v-else
          :label="$t('workReports.generate.form.dateRange')"
          prop="dateRange"
        >
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            :range-separator="$t('workReports.generate.form.rangeSeparator')"
            :start-placeholder="$t('workReports.generate.form.startDate')"
            :end-placeholder="$t('workReports.generate.form.endDate')"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 300px"
            @change="handleDateRangeChange"
          />
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            size="large"
            :loading="reportGenerating"
            @click="handleGenerate"
          >
            <el-icon><Star /></el-icon>
            {{ reportGenerating ? $t('workReports.generate.form.generating') : $t('workReports.generate.form.generateButton') }}
          </el-button>
          <el-button size="large" @click="resetForm">
            <el-icon><Refresh /></el-icon>
            {{ $t('workReports.generate.form.resetButton') }}
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 快速生成选项 -->
      <el-divider content-position="center">{{ $t('workReports.generate.quickOptions.title') }}</el-divider>
      <div class="quick-options">
        <el-button
          v-for="option in quickOptions"
          :key="option.key"
          :type="option.type"
          :loading="reportGenerating"
          @click="option.action"
        >
          <el-icon>
            <component :is="option.icon" />
          </el-icon>
          {{ option.label }}
        </el-button>
      </div>
    </el-card>

    <!-- 生成结果区域 -->
    <el-card v-if="generatedReport" class="report-result">
      <template #header>
        <div class="result-header">
          <div class="result-title">
            <h3>{{ generatedReport.title || '生成的报告' }}</h3>
            <div class="result-meta">
              <el-tag type="success">{{ generatedReport.typeDescription }}</el-tag>
              <span class="meta-item">
                <el-icon><Calendar /></el-icon>
                {{ formatDateRange(generatedReport) }}
              </span>
              <span class="meta-item">
                <el-icon><Document /></el-icon>
                {{ generatedReport.recordCount }} 条记录
              </span>
              <span class="meta-item">
                <el-icon><Clock /></el-icon>
                {{ generatedReport.formattedTimeSpent }}
              </span>
            </div>
          </div>
          <div class="result-actions">
            <el-button
              type="success"
              @click="showSaveDialog = true"
              :loading="saving"
            >
              <el-icon><DocumentAdd /></el-icon>
              保存到历史
            </el-button>
            <el-button @click="copyReport">
              <el-icon><CopyDocument /></el-icon>
              复制
            </el-button>
            <el-button @click="exportReport">
              <el-icon><Download /></el-icon>
              导出
            </el-button>
            <el-button @click="regenerateReport">
              <el-icon><Refresh /></el-icon>
              重新生成
            </el-button>
            <el-button type="primary" @click="clearReport">
              <el-icon><Plus /></el-icon>
              新建报告
            </el-button>
          </div>
        </div>
      </template>

      <div class="report-content">
        <div class="report-actions-bar">
          <el-button-group>
            <el-button
              :type="viewMode === 'preview' ? 'primary' : ''"
              :icon="View"
              @click="viewMode = 'preview'"
            >
              预览模式
            </el-button>
            <el-button
              :type="viewMode === 'edit' ? 'primary' : ''"
              :icon="Edit"
              @click="viewMode = 'edit'"
            >
              编辑模式
            </el-button>
          </el-button-group>
        </div>

        <!-- 预览模式 -->
        <div v-if="viewMode === 'preview'" class="preview-container">
          <MdPreview
            :key="`report-preview-${generatedReport.id || Date.now()}`"
            :modelValue="currentContent"
            :theme="previewTheme"
            language="zh-CN"
          />
        </div>

        <!-- 编辑模式 -->
        <div v-else class="edit-container">
          <MdEditor
            v-model="editableContent"
            :placeholder="'编辑报告内容...'"
            :preview="true"
            :toolbars="editorToolbars"
            :theme="editorTheme"
            language="zh-CN"
            @onChange="handleContentChange"
            @onSave="handleSaveEdit"
          />
          <div class="edit-actions">
            <el-button @click="handleCancelEdit">取消</el-button>
            <el-button type="primary" @click="handleSaveEdit">保存修改</el-button>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 加载状态 -->
    <div v-if="reportGenerating && !generatedReport" class="generating-state">
      <el-card>
        <div class="generating-content">
          <el-icon class="generating-icon" size="48">
            <Loading />
          </el-icon>
          <h3>AI正在生成报告...</h3>
          <p>正在调用AI服务分析您的工作记录，这可能需要30-60秒时间，请耐心等待</p>
          <el-progress :percentage="generateProgress" :show-text="false" />
        </div>
      </el-card>
    </div>

    <!-- 保存报告对话框 -->
    <el-dialog
      v-model="showSaveDialog"
      title="保存报告到历史记录"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form :model="saveForm" :rules="saveRules" ref="saveFormRef" label-width="80px">
        <el-form-item label="报告标题" prop="title">
          <el-input
            v-model="saveForm.title"
            placeholder="请输入报告标题（可选，留空则自动生成）"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="报告类型">
          <el-tag :type="getReportTypeTagType(reportType)">
            {{ getReportTypeText(reportType) }}
          </el-tag>
        </el-form-item>
        <el-form-item label="时间范围">
          <span>{{ formatDateRange() }}</span>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showSaveDialog = false">取消</el-button>
          <el-button
            type="primary"
            @click="handleSaveReport"
            :loading="saving"
          >
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, watch, markRaw } from 'vue'
import { useI18n } from 'vue-i18n'
import { useWorkReportStore } from '@/stores/workReportStore'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import {
  Star,
  Refresh,
  Calendar,
  Document,
  Clock,
  CopyDocument,
  Download,
  Plus,
  Loading,
  Timer,
  View,
  Edit,
  DocumentAdd,
  MagicStick
} from '@element-plus/icons-vue'
import { createReportTypeOptions, ReportType } from '@/types/workReport'
import { MdEditor, MdPreview } from 'md-editor-v3'
import 'md-editor-v3/lib/style.css'
import 'md-editor-v3/lib/preview.css'

const { t } = useI18n()
const workReportStore = useWorkReportStore()

// 国际化的报告类型选项
const reportTypeOptions = computed(() => createReportTypeOptions(t))

// 响应式数据
const formRef = ref<FormInstance>()
const generateForm = ref({
  type: ReportType.DAILY,
  startDate: '',
  endDate: ''
})
const dateRange = ref<[string, string] | null>(null)
const generateProgress = ref(0)

// 编辑器相关
const viewMode = ref<'preview' | 'edit'>('preview')
const editableContent = ref('')
const originalContent = ref('')

// 保存相关
const showSaveDialog = ref(false)
const saving = ref(false)
const saveForm = ref({
  title: ''
})
const saveFormRef = ref()
const saveRules = {
  title: [
    { max: 100, message: '标题长度不能超过100个字符', trigger: 'blur' }
  ]
}

// 表单验证规则
const generateRules: FormRules = {
  type: [
    { required: true, message: '请选择报告类型', trigger: 'change' }
  ],
  startDate: [
    { required: true, message: '请选择日期', trigger: 'change' }
  ]
}

// 计算属性
const generatedReport = computed(() => workReportStore.generatedReport)
const reportGenerating = computed(() => workReportStore.reportGenerating)

// 编辑器配置
const editorTheme = computed(() => {
  return document.documentElement.classList.contains('dark') ? 'dark' : 'light'
})

const previewTheme = computed(() => {
  return document.documentElement.classList.contains('dark') ? 'dark' : 'light'
})

const editorToolbars = [
  'bold', 'underline', 'italic', '-',
  'title', 'strikeThrough', 'sub', 'sup', 'quote',
  'unorderedList', 'orderedList', 'task', '-',
  'codeRow', 'code', 'link', 'image', 'table', '-',
  'revoke', 'next', 'save', '=',
  'pageFullscreen', 'fullscreen', 'preview', 'catalog'
]

// 当前显示的内容
const currentContent = computed(() => {
  return generatedReport.value?.content || ''
})

// 快速生成选项
const quickOptions = computed(() => [
  {
    key: 'today',
    label: t('workReports.generate.quickOptions.dailyReport'),
    type: 'primary',
    icon: markRaw(Calendar), // 使用markRaw避免图标组件被响应式包装
    action: generateTodayReport
  },
  {
    key: 'week',
    label: t('workReports.generate.quickOptions.weeklyReport'),
    type: 'success',
    icon: markRaw(Timer), // 使用markRaw避免图标组件被响应式包装
    action: generateWeekReport
  },
  {
    key: 'month',
    label: t('workReports.generate.quickOptions.monthlyReport'),
    type: 'warning',
    icon: markRaw(Calendar), // 使用markRaw避免图标组件被响应式包装
    action: generateMonthReport
  }
])

// 进度条定时器
let progressTimer: NodeJS.Timeout | null = null

// 监听生成状态，模拟进度
watch(reportGenerating, (isGenerating) => {
  if (isGenerating) {
    generateProgress.value = 0
    progressTimer = setInterval(() => {
      generateProgress.value += 10
      if (generateProgress.value >= 90) {
        if (progressTimer) {
          clearInterval(progressTimer)
          progressTimer = null
        }
      }
    }, 200)
  } else {
    // 清理定时器
    if (progressTimer) {
      clearInterval(progressTimer)
      progressTimer = null
    }
    generateProgress.value = 100
  }
})

// 获取类型描述
const getTypeDescription = (type: ReportType) => {
  const option = reportTypeOptions.value.find(opt => opt.value === type)
  return option?.description || ''
}

// 处理类型变化
const handleTypeChange = (type: ReportType) => {
  if (type === ReportType.DAILY) {
    generateForm.value.startDate = new Date().toISOString().split('T')[0]
    generateForm.value.endDate = ''
    dateRange.value = null
  } else {
    generateForm.value.startDate = ''
    generateForm.value.endDate = ''
    dateRange.value = null
  }
}

// 处理日期范围变化
const handleDateRangeChange = (dates: [string, string] | null) => {
  if (dates) {
    generateForm.value.startDate = dates[0]
    generateForm.value.endDate = dates[1]
  } else {
    generateForm.value.startDate = ''
    generateForm.value.endDate = ''
  }
}

// 生成报告
const handleGenerate = async () => {
  if (!formRef.value || reportGenerating.value) return // 防止重复点击

  try {
    await formRef.value.validate()

    const requestData = {
      type: generateForm.value.type,
      startDate: generateForm.value.startDate,
      endDate: generateForm.value.endDate || undefined
    }

    await workReportStore.generateReport(requestData)
  } catch (error) {
    console.error('生成报告失败:', error)
    // 显示具体的错误信息
    let errorMessage = t('workReports.generate.errors.generateFailed')
    if (error.response && error.response.data && error.response.data.message) {
      errorMessage = error.response.data.message
    } else if (error.message) {
      errorMessage = error.message
    }
    ElMessage.error(errorMessage)
  }
}

// 快速生成今日日报
async function generateTodayReport() {
  if (reportGenerating.value) return // 防止重复点击

  try {
    await workReportStore.generateTodayReport()
  } catch (error) {
    console.error('生成今日日报失败:', error)
  }
}

// 快速生成本周周报
async function generateWeekReport() {
  if (reportGenerating.value) return // 防止重复点击

  try {
    const today = new Date()
    const startOfWeek = new Date(today.setDate(today.getDate() - today.getDay() + 1))
    const endOfWeek = new Date(today.setDate(today.getDate() - today.getDay() + 7))

    await workReportStore.generateReport({
      type: ReportType.WEEKLY,
      startDate: startOfWeek.toISOString().split('T')[0],
      endDate: endOfWeek.toISOString().split('T')[0]
    })
  } catch (error) {
    console.error('生成本周周报失败:', error)
  }
}

// 快速生成本月月报
async function generateMonthReport() {
  if (reportGenerating.value) return // 防止重复点击

  try {
    const today = new Date()
    const startOfMonth = new Date(today.getFullYear(), today.getMonth(), 1)
    const endOfMonth = new Date(today.getFullYear(), today.getMonth() + 1, 0)

    await workReportStore.generateReport({
      type: ReportType.MONTHLY,
      startDate: startOfMonth.toISOString().split('T')[0],
      endDate: endOfMonth.toISOString().split('T')[0]
    })
  } catch (error) {
    console.error('生成本月月报失败:', error)
  }
}

// 重置表单
const resetForm = () => {
  generateForm.value = {
    type: ReportType.DAILY,
    startDate: new Date().toISOString().split('T')[0],
    endDate: ''
  }
  dateRange.value = null
  formRef.value?.clearValidate()
}

// 复制报告
const copyReport = async () => {
  if (!generatedReport.value?.content) return
  
  try {
    await navigator.clipboard.writeText(generatedReport.value.content)
    ElMessage.success('报告内容已复制到剪贴板')
  } catch (error) {
    ElMessage.error('复制失败')
  }
}

// 导出报告
const exportReport = () => {
  if (!generatedReport.value) return
  
  const content = generatedReport.value.content
  const title = generatedReport.value.title || '工作报告'
  const blob = new Blob([content], { type: 'text/markdown' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = `${title}.md`
  a.click()
  URL.revokeObjectURL(url)
  ElMessage.success('报告已导出')
}

// 重新生成报告
const regenerateReport = () => {
  if (generatedReport.value) {
    generateForm.value.type = generatedReport.value.type
    generateForm.value.startDate = generatedReport.value.startDate
    generateForm.value.endDate = generatedReport.value.endDate || ''
    
    if (generatedReport.value.type !== ReportType.DAILY && generatedReport.value.endDate) {
      dateRange.value = [generatedReport.value.startDate, generatedReport.value.endDate]
    }
  }
  
  workReportStore.clearGeneratedReport()
}

// 清除报告
const clearReport = () => {
  workReportStore.clearGeneratedReport()
  resetForm()
}

// 编辑相关方法
const handleContentChange = (value: string) => {
  editableContent.value = value
}

const handleSaveEdit = async () => {
  try {
    // 这里可以调用API保存编辑后的内容
    // await workReportStore.updateReportContent(generatedReport.value.id, editableContent.value)

    // 临时更新本地内容
    if (generatedReport.value) {
      generatedReport.value.content = editableContent.value
    }

    viewMode.value = 'preview'
    ElMessage.success(t('workReports.generate.messages.saveSuccess'))
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error(t('workReports.generate.messages.saveFailed'))
  }
}

const handleCancelEdit = () => {
  editableContent.value = currentContent.value
  viewMode.value = 'preview'
}

// 监听编辑模式切换
watch(viewMode, (newMode) => {
  if (newMode === 'edit') {
    editableContent.value = currentContent.value
    originalContent.value = currentContent.value
  }
})

// 保存报告到历史记录
const handleSaveReport = async () => {
  if (!saveFormRef.value || !generatedReport.value) return

  try {
    await saveFormRef.value.validate()
    saving.value = true

    const saveData = {
      type: generatedReport.value.type,
      startDate: generatedReport.value.startDate,
      endDate: generatedReport.value.endDate || generatedReport.value.startDate,
      content: currentContent.value,
      title: saveForm.value.title.trim() || undefined
    }

    await workReportStore.saveReportToHistory(saveData)

    ElMessage.success(t('workReports.generate.messages.saveToHistorySuccess'))
    showSaveDialog.value = false
    saveForm.value.title = ''
  } catch (error: any) {
    console.error('保存报告失败:', error)
    ElMessage.error(error.message || t('workReports.generate.messages.saveToHistoryFailed'))
  } finally {
    saving.value = false
  }
}

// 获取报告类型文本
const getReportTypeText = (type: string) => {
  const typeMap: Record<string, string> = {
    'DAILY': t('workReports.generate.reportTypes.daily'),
    'WEEKLY': t('workReports.generate.reportTypes.weekly'),
    'MONTHLY': t('workReports.generate.reportTypes.monthly')
  }
  return typeMap[type] || type
}

// 获取报告类型标签类型
const getReportTypeTagType = (type: string) => {
  const typeMap: Record<string, string> = {
    'DAILY': 'success',
    'WEEKLY': 'warning',
    'MONTHLY': 'danger'
  }
  return typeMap[type] || ''
}

// 计算当前报告类型
const reportType = computed(() => {
  return generatedReport.value?.type || generateForm.value.type
})

// 格式化日期范围
const formatDateRange = () => {
  if (!generatedReport.value) return ''

  if (generatedReport.value.type === 'DAILY') {
    return generatedReport.value.startDate
  }
  return `${generatedReport.value.startDate} 至 ${generatedReport.value.endDate || generatedReport.value.startDate}`
}

// 组件挂载时初始化
onMounted(() => {
  resetForm()
})

// 组件卸载时清理
onUnmounted(() => {
  if (progressTimer) {
    clearInterval(progressTimer)
    progressTimer = null
  }
})
</script>

<style scoped lang="scss">
.generate-view {
  height: 100%;
  overflow: auto;
}

.generate-config {
  margin-bottom: 20px;

  .card-header {
    h3 {
      margin: 0 0 8px 0;
      display: flex;
      align-items: center;
      gap: 8px;
      font-size: 18px;
      color: var(--el-text-color-primary);
    }

    p {
      margin: 0;
      color: var(--el-text-color-regular);
      font-size: 14px;
    }
  }

  .type-description {
    margin-top: 8px;
    font-size: 12px;
    color: var(--el-text-color-regular);
  }

  .quick-options {
    display: flex;
    gap: 12px;
    justify-content: center;
  }
}

.report-result {
  .result-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;

    .result-title {
      flex: 1;

      h3 {
        margin: 0 0 12px 0;
        font-size: 20px;
        color: var(--el-text-color-primary);
      }

      .result-meta {
        display: flex;
        gap: 16px;
        align-items: center;
        flex-wrap: wrap;

        .meta-item {
          display: flex;
          align-items: center;
          gap: 4px;
          font-size: 14px;
          color: var(--el-text-color-regular);
        }
      }
    }

    .result-actions {
      display: flex;
      gap: 8px;
      flex-wrap: wrap;
    }
  }

  .report-content {
    margin-top: 20px;
    padding-top: 20px;
    border-top: 1px solid var(--el-border-color-lighter);

    .report-actions-bar {
      margin-bottom: 16px;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .preview-container {
      border: 1px solid var(--el-border-color);
      border-radius: 6px;
      overflow: hidden;
      padding: 8px;
      min-height: 500px;
    }

    .edit-container {
      border: 1px solid var(--el-border-color);
      border-radius: 6px;
      overflow: hidden;

      :deep(.md-editor) {
        height: 600px;
      }

      .edit-actions {
        padding: 12px 16px;
        border-top: 1px solid var(--el-border-color);
        background: var(--el-bg-color-page);
        display: flex;
        justify-content: flex-end;
        gap: 8px;
      }
    }

    .markdown-content {
      line-height: 1.6;
      color: var(--el-text-color-primary);

      :deep(h1), :deep(h2), :deep(h3), :deep(h4), :deep(h5), :deep(h6) {
        margin: 20px 0 12px 0;
        color: var(--el-text-color-primary);
      }

      :deep(p) {
        margin: 12px 0;
      }

      :deep(ul), :deep(ol) {
        margin: 12px 0;
        padding-left: 24px;
      }

      :deep(li) {
        margin: 6px 0;
      }

      :deep(blockquote) {
        margin: 16px 0;
        padding: 12px 16px;
        background: var(--el-bg-color-page);
        border-left: 4px solid var(--el-color-primary);
        border-radius: 4px;
      }

      :deep(code) {
        padding: 2px 6px;
        background: var(--el-bg-color-page);
        border-radius: 4px;
        font-family: 'Courier New', monospace;
      }

      :deep(pre) {
        margin: 16px 0;
        padding: 16px;
        background: var(--el-bg-color-page);
        border-radius: 8px;
        overflow-x: auto;
      }

      :deep(table) {
        width: 100%;
        border-collapse: collapse;
        margin: 16px 0;
      }

      :deep(th), :deep(td) {
        padding: 8px 12px;
        border: 1px solid var(--el-border-color-light);
        text-align: left;
      }

      :deep(th) {
        background: var(--el-bg-color-page);
        font-weight: 600;
      }
    }
  }
}

.generating-state {
  .generating-content {
    text-align: center;
    padding: 40px 20px;

    .generating-icon {
      color: var(--el-color-primary);
      animation: spin 1s linear infinite;
    }

    h3 {
      margin: 16px 0 8px 0;
      color: var(--el-text-color-primary);
    }

    p {
      margin: 0 0 24px 0;
      color: var(--el-text-color-regular);
    }
  }
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}
</style>
